<template>
  <div class="order-monitor">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>订单监控</span>
          <el-button-group>
            <el-button type="primary" @click="handleBatchProcess"
              >批量处理</el-button
            >
            <el-button type="success" @click="exportData">导出数据</el-button>
            <el-button type="warning" @click="toggleAutoRefresh">
              {{ isAutoRefresh ? "停止刷新" : "自动刷新" }}
            </el-button>
          </el-button-group>
        </div>
      </template>

      <!-- 统计卡片 -->
      <el-row :gutter="20" class="statistics-cards">
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-value">{{ statistics.pending }}</div>
            <div class="stat-label">待处理订单</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card warning">
            <div class="stat-value">{{ statistics.processing }}</div>
            <div class="stat-label">处理中订单</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card success">
            <div class="stat-value">{{ statistics.completed }}</div>
            <div class="stat-label">今日完成</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card info">
            <div class="stat-value">¥{{ statistics.amount }}</div>
            <div class="stat-label">今日交易额</div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="订单号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item label="订单类型">
          <el-select v-model="searchForm.type" placeholder="请选择订单类型">
            <el-option label="门票订单" value="ticket" />
            <el-option label="酒店订单" value="hotel" />
            <el-option label="套餐订单" value="package" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.status" placeholder="请选择订单状态">
            <el-option label="待支付" value="unpaid" />
            <el-option label="已支付" value="paid" />
            <el-option label="已确认" value="confirmed" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
            <el-option label="退款中" value="refunding" />
            <el-option label="已退款" value="refunded" />
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="orderList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderNo" label="订单号" width="180" />
        <el-table-column prop="type" label="订单类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeTag(row.type)">
              {{ getTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="productName"
          label="商品名称"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column prop="amount" label="订单金额" width="120">
          <template #default="{ row }"> ¥{{ row.amount }} </template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="payTime" label="支付时间" width="160" />
        <el-table-column prop="createTime" label="下单时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                type="primary"
                size="small"
                :disabled="!canProcess(row.status)"
                @click="handleProcess(row)"
              >
                处理
              </el-button>
              <el-button
                type="warning"
                size="small"
                :disabled="!canRefund(row.status)"
                @click="handleRefund(row)"
              >
                退款
              </el-button>
              <el-button type="info" size="small" @click="viewDetail(row)">
                详情
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
        
        <template #empty>
          <div class="empty-state">
            <el-empty 
              description="暂无订单数据" 
              :image-size="200"
            >
              <div class="empty-text">暂无待处理订单</div>
              <div class="empty-subtext">所有订单都已经处理完毕</div>
            </el-empty>
          </div>
        </template>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 处理对话框 -->
    <el-dialog v-model="processDialogVisible" title="处理订单" width="500px">
      <el-form
        ref="processFormRef"
        :model="processForm"
        :rules="processRules"
        label-width="100px"
      >
        <el-form-item label="处理结果" prop="result">
          <el-select v-model="processForm.result" placeholder="请选择处理结果">
            <el-option label="确认订单" value="confirm" />
            <el-option label="完成订单" value="complete" />
            <el-option label="取消订单" value="cancel" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理说明" prop="remark">
          <el-input
            v-model="processForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入处理说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="processDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitProcess">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 退款对话框 -->
    <el-dialog v-model="refundDialogVisible" title="订单退款" width="500px">
      <el-form
        ref="refundFormRef"
        :model="refundForm"
        :rules="refundRules"
        label-width="100px"
      >
        <el-form-item label="退款金额" prop="amount">
          <el-input-number
            v-model="refundForm.amount"
            :min="0"
            :max="currentOrder.amount"
            :precision="2"
            :step="0.01"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="退款原因" prop="reason">
          <el-input
            v-model="refundForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入退款原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="refundDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRefund">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="订单详情" width="800px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单号">{{
          currentOrder.orderNo
        }}</el-descriptions-item>
        <el-descriptions-item label="订单类型">
          <el-tag :type="getTypeTag(currentOrder.type)">
            {{ getTypeLabel(currentOrder.type) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="商品名称">{{
          currentOrder.productName
        }}</el-descriptions-item>
        <el-descriptions-item label="订单金额"
          >¥{{ currentOrder.amount }}</el-descriptions-item
        >
        <el-descriptions-item label="订单状态">
          <el-tag :type="getStatusTag(currentOrder.status)">
            {{ getStatusLabel(currentOrder.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="支付方式">{{
          currentOrder.payMethod
        }}</el-descriptions-item>
        <el-descriptions-item label="下单时间">{{
          currentOrder.createTime
        }}</el-descriptions-item>
        <el-descriptions-item label="支付时间">{{
          currentOrder.payTime
        }}</el-descriptions-item>
        <el-descriptions-item label="联系人">{{
          currentOrder.contactName
        }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{
          currentOrder.contactPhone
        }}</el-descriptions-item>
        <el-descriptions-item label="使用日期" :span="2">{{
          currentOrder.useDate
        }}</el-descriptions-item>
        <el-descriptions-item label="备注信息" :span="2">{{
          currentOrder.remark || "无"
        }}</el-descriptions-item>
      </el-descriptions>

      <div class="order-timeline mt-4">
        <h4>订单日志</h4>
        <el-timeline>
          <el-timeline-item
            v-for="(activity, index) in currentOrder.activities"
            :key="index"
            :timestamp="activity.time"
            :type="activity.type"
          >
            {{ activity.content }}
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";

// 统计数据
const statistics = reactive({
  pending: 0,
  processing: 0,
  completed: 0,
  amount: 0,
});

// 自动刷新
const isAutoRefresh = ref(false);
let refreshTimer = null;

// 搜索表单
const searchForm = reactive({
  orderNo: "",
  type: "",
  status: "",
  dateRange: [],
});

// 表格数据
const loading = ref(false);
const orderList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedOrders = ref([]);

// 处理对话框
const processDialogVisible = ref(false);
const processFormRef = ref(null);
const processForm = reactive({
  result: "",
  remark: "",
});

// 处理表单验证规则
const processRules = {
  result: [{ required: true, message: "请选择处理结果", trigger: "change" }],
  remark: [{ required: true, message: "请输入处理说明", trigger: "blur" }],
};

// 退款对话框
const refundDialogVisible = ref(false);
const refundFormRef = ref(null);
const refundForm = reactive({
  amount: 0,
  reason: "",
});

// 退款表单验证规则
const refundRules = {
  amount: [{ required: true, message: "请输入退款金额", trigger: "blur" }],
  reason: [{ required: true, message: "请输入退款原因", trigger: "blur" }],
};

// 详情对话框
const detailDialogVisible = ref(false);
const currentOrder = ref({});

// 获取订单类型标签
const getTypeLabel = (type) => {
  const types = {
    ticket: "门票订单",
    hotel: "酒店订单",
    package: "套餐订单",
  };
  return types[type] || type;
};

// 获取订单类型标签样式
const getTypeTag = (type) => {
  const types = {
    ticket: "",
    hotel: "success",
    package: "warning",
  };
  return types[type] || "";
};

// 获取状态标签
const getStatusLabel = (status) => {
  const statuses = {
    unpaid: "待支付",
    paid: "已支付",
    confirmed: "已确认",
    completed: "已完成",
    cancelled: "已取消",
    refunding: "退款中",
    refunded: "已退款",
  };
  return statuses[status] || status;
};

// 获取状态标签样式
const getStatusTag = (status) => {
  const statuses = {
    unpaid: "info",
    paid: "warning",
    confirmed: "success",
    completed: "success",
    cancelled: "danger",
    refunding: "warning",
    refunded: "info",
  };
  return statuses[status] || "";
};

// 判断是否可以处理订单
const canProcess = (status) => {
  return ["paid", "confirmed"].includes(status);
};

// 判断是否可以退款
const canRefund = (status) => {
  return ["paid", "confirmed"].includes(status);
};

// 切换自动刷新
const toggleAutoRefresh = () => {
  isAutoRefresh.value = !isAutoRefresh.value;
  if (isAutoRefresh.value) {
    refreshTimer = setInterval(() => {
      handleSearch();
    }, 30000); // 每30秒刷新一次
  } else {
    clearInterval(refreshTimer);
  }
};

// 搜索
const handleSearch = () => {
  // 实现搜索逻辑
  fetchData();
};

// 获取数据列表
const fetchData = async () => {
  loading.value = true;
  try {
    // 构建请求参数
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      orderNo: searchForm.orderNo || undefined,
      type: searchForm.type || undefined,
      status: searchForm.status || undefined,
      startDate: searchForm.dateRange && searchForm.dateRange[0] ? searchForm.dateRange[0] : undefined,
      endDate: searchForm.dateRange && searchForm.dateRange[1] ? searchForm.dateRange[1] : undefined,
    };

    // 获取统计数据
    const statsResponse = await axios.get("/admin/orders/monitor/statistics");
    if (statsResponse) {
      statistics.pending = statsResponse.pending || 0;
      statistics.processing = statsResponse.processing || 0;
      statistics.completed = statsResponse.completed || 0;
      statistics.amount = statsResponse.amount || 0;
    }

    // 调用API获取数据
    const response = await axios.get("/admin/orders/monitor", { params });
    
    // 检查响应是否存在
    if (response) {
      // 不管是否有数据，都使用后端返回的结果
      orderList.value = Array.isArray(response.records) ? response.records : [];
      total.value = response.total || 0;
    } else {
      // 响应对象不存在，设置为空数组
      orderList.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error("获取订单监控数据失败：", error);
    ElMessage.error("获取数据失败");
    
    statistics.pending = 5;
    statistics.processing = 3;
    statistics.completed = 12;
    statistics.amount = 3680;
    
    orderList.value = [
      {
        id: 1,
        orderNo: "T202403150001",
        type: "ticket",
        productName: "贵港园博园门票",
        amount: 160,
        status: "paid",
        createTime: "2024-03-15 10:30:00",
        payTime: "2024-03-15 10:35:00",
        contactName: "张三",
        contactPhone: "13800138000",
        payMethod: "微信支付",
        useDate: "2024-03-20",
        quantity: 2,
        unitPrice: 80,
        remark: "需要导游讲解服务",
        activities: [
          {
            time: "2024-03-15 10:30:00",
            type: "info",
            content: "用户创建订单"
          },
          {
            time: "2024-03-15 10:35:00",
            type: "success",
            content: "用户完成支付"
          }
        ]
      },
      {
        id: 2,
        orderNo: "H202403140002",
        type: "hotel",
        productName: "贵港江景酒店豪华套房",
        amount: 680,
        status: "confirmed",
        createTime: "2024-03-14 15:20:00",
        payTime: "2024-03-14 15:22:00",
        contactName: "李四",
        contactPhone: "13900139000",
        payMethod: "支付宝",
        checkInDate: "2024-03-18",
        checkOutDate: "2024-03-20",
        nights: 2,
        guests: 2,
        roomType: "豪华套房",
        remark: "希望安排高层江景房",
        activities: [
          {
            time: "2024-03-14 15:20:00",
            type: "info",
            content: "用户创建订单"
          },
          {
            time: "2024-03-14 15:22:00",
            type: "success",
            content: "用户完成支付"
          },
          {
            time: "2024-03-14 16:00:00",
            type: "warning",
            content: "酒店确认订单"
          }
        ]
      },
      {
        id: 3,
        orderNo: "P202403130003",
        type: "package",
        productName: "贵港三日游文化体验套餐",
        amount: 1580,
        status: "unpaid",
        createTime: "2024-03-13 09:45:00",
        payTime: "",
        contactName: "王五",
        contactPhone: "13700137000",
        payMethod: "",
        startDate: "2024-03-25",
        endDate: "2024-03-27",
        days: 3,
        people: 2,
        packageItems: [
          "贵港园博园门票",
          "江滨公园一日游",
          "古镇文化体验",
          "特色美食品尝"
        ],
        remark: "希望安排中文导游",
        activities: [
          {
            time: "2024-03-13 09:45:00",
            type: "info",
            content: "用户创建订单"
          }
        ]
      },
      {
        id: 4,
        orderNo: "T202403120004",
        type: "ticket",
        productName: "贵港市博物馆特展门票",
        amount: 120,
        status: "refunding",
        createTime: "2024-03-12 14:25:00",
        payTime: "2024-03-12 14:30:00",
        contactName: "赵六",
        contactPhone: "13600136000",
        payMethod: "银联支付",
        useDate: "2024-03-15",
        quantity: 3,
        unitPrice: 40,
        refundApplyTime: "2024-03-13 10:20:00",
        refundReason: "行程变更无法按时前往",
        remark: "",
        activities: [
          {
            time: "2024-03-12 14:25:00",
            type: "info",
            content: "用户创建订单"
          },
          {
            time: "2024-03-12 14:30:00",
            type: "success",
            content: "用户完成支付"
          },
          {
            time: "2024-03-13 10:20:00",
            type: "warning",
            content: "用户申请退款"
          },
          {
            time: "2024-03-13 11:15:00",
            type: "info",
            content: "客服审核退款申请"
          }
        ]
      }
    ];
    total.value = orderList.value.length;
  } finally {
    loading.value = false;
  }
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = "";
  });
  handleSearch();
};

// 处理选择变化
const handleSelectionChange = (val) => {
  selectedOrders.value = val;
};

// 批量处理
const handleBatchProcess = () => {
  if (selectedOrders.value.length === 0) {
    ElMessage.warning("请选择要处理的订单");
    return;
  }
  // 实现批量处理逻辑
};

// 导出数据
const exportData = () => {
  // 实现导出逻辑
};

// 处理订单
const handleProcess = (row) => {
  currentOrder.value = row;
  processForm.result = "";
  processForm.remark = "";
  processDialogVisible.value = true;
};

// 退款处理
const handleRefund = (row) => {
  currentOrder.value = row;
  refundForm.amount = row.amount;
  refundForm.reason = "";
  refundDialogVisible.value = true;
};

// 查看详情
const viewDetail = (row) => {
  currentOrder.value = row;
  detailDialogVisible.value = true;
};

// 提交处理
const submitProcess = () => {
  processFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        // 实现提交处理的逻辑
        ElMessage.success("处理成功");
        processDialogVisible.value = false;
        handleSearch();
      } catch (error) {
        console.error("处理失败：", error);
        ElMessage.error("处理失败");
      }
    }
  });
};

// 提交退款
const submitRefund = () => {
  refundFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        // 实现提交退款的逻辑
        ElMessage.success("退款申请提交成功");
        refundDialogVisible.value = false;
        handleSearch();
      } catch (error) {
        console.error("退款申请失败：", error);
        ElMessage.error("退款申请失败");
      }
    }
  });
};

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  handleSearch();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  handleSearch();
};

// 页面加载时获取数据
onMounted(() => {
  handleSearch();
});

// 组件卸载前清除定时器
onBeforeUnmount(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer);
  }
});
</script>

<style scoped>
.order-monitor {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.statistics-cards {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  padding: 20px;
}

.stat-card.warning .stat-value {
  color: #e6a23c;
}

.stat-card.success .stat-value {
  color: #67c23a;
}

.stat-card.info .stat-value {
  color: #409eff;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.mt-4 {
  margin-top: 20px;
}

.order-timeline {
  margin-top: 20px;
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.empty-state {
  text-align: center;
  padding: 20px;
}

.empty-text {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.empty-subtext {
  font-size: 14px;
  color: #909399;
}
</style>
